//
//  PersistanceManager.m
//  Beautician
//
//  Created by wangjiayu on 4/16/15.
//  Copyright (c) 2015 XuShi Technology Co.,Ltd. All rights reserved.
//

#import "PersistanceManager.h"

#define KcookieKey @"kCookie"

@implementation PersistanceManager

+ (NSString *)dataDirectoryPath {
    NSString *documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    return [documentsDirectoryPath stringByAppendingPathComponent:@"data"];
}

+ (NSString *)tempDirectoryPath {
    NSString *documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    return [documentsDirectoryPath stringByAppendingPathComponent:@"data"];
}

+ (NSString *)filePathWithIdentifier:(NSString *)identifier {
    return [[self dataDirectoryPath] stringByAppendingPathComponent:identifier];
}

+ (void)saveObject:(id)object identifier:(NSString *)identifier {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:[self dataDirectoryPath]]) {
        NSError *error;
        
        //--- 将Library/Cache/data目录下缓存的数据移到Documents/data下,防止设备低内存时数据被删除 ---
        if ([fileManager fileExistsAtPath:[self tempDirectoryPath]]) {
            [self copyFileWithFromPath:[self tempDirectoryPath] toPath:[self dataDirectoryPath]];
        }
        
        if (![fileManager createDirectoryAtPath:[self dataDirectoryPath] withIntermediateDirectories:YES attributes:nil error:&error]) {
            NSLog(@"create data directory error: %@", error);
        }
    }
    
    if (![NSKeyedArchiver archiveRootObject:object toFile:[self filePathWithIdentifier:identifier]]) {
        NSLog(@"saveObject error: %@", identifier);
    }
}

+ (void)removeObjectWithIdentifier:(NSString *)identifier {
    NSError *error;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager removeItemAtPath:[self filePathWithIdentifier:identifier] error:&error]) {
        NSLog(@"removeObjectWithIdentifier: %@", error);
    }
}

+ (id)fetchObjectWithIdentifier:(NSString *)identifier {
    //--- 将Library/Cache/data目录下缓存的数据移到Documents/data下,防止设备低内存时数据被删除 ---
    if ([[NSFileManager defaultManager] fileExistsAtPath:[self tempDirectoryPath]]) {
        [self copyFileWithFromPath:[self tempDirectoryPath] toPath:[self dataDirectoryPath]];
    }
    
    NSString *path = [self filePathWithIdentifier:identifier];
    @try {
        return [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    } @catch (NSException *exception) {
        [self removeObjectWithIdentifier:identifier];
        return nil;
    } @finally {
        
    }
}

///保存 cookies
///cookie 存储规则：同key更新，异key新增
+ (void)saveCookieWithURL:(NSURL *)url {

    //并发导致的问题吗:都是在主线程调的
    //NSLog(@"%s===%@",__func__,NSThread.currentThread);
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:url];
    //NSLog(@"cookies count %ld",cookies.count);

    //本地之前的
    NSMutableArray *oldCookies = [self getsaveCookieDataArray];

    //需要判断是否存在:删除old中存在的同key数据
    [cookies enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSHTTPCookie * cookie = obj;
        [oldCookies enumerateObjectsUsingBlock:^(id  _Nonnull oldobj, NSUInteger oldidx, BOOL * _Nonnull stop) {
            NSHTTPCookie * oldcookie = oldobj;
            //存在替换
            if ([oldcookie.name isEqualToString:cookie.name]) {
                [oldCookies removeObject:oldcookie];
            }
        }];
    }];
    //将新的添加到数据中
    [oldCookies addObjectsFromArray:cookies];
//    NSLog(@"all cookie count-- %ld data is%@",oldCookies.count,oldCookies);
    if (oldCookies.count == 0){
        return;
    }

    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:oldCookies];
//    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:cookies];
    [[self class] saveObject:data identifier:KcookieKey];
}

///程序重新启动，加载cookie
+ (void)loadCookie {

//    if ([GlobalConst isLoged]) {
        NSData *data = [[self class] fetchObjectWithIdentifier:KcookieKey];

        if ([data isKindOfClass:[NSData class]]) {
            if ([data length]) {
                NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:data];
                for (NSHTTPCookie *cookie in cookies) {
                    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
                }
            }
        }
//    }
}

//获取存储的cookie数据
+(NSMutableArray *)getsaveCookieDataArray{
    NSMutableArray *cookieArray = [NSMutableArray array];
//    if ([GlobalConst isLoged]) {
        NSData *cookieData = [[self class] fetchObjectWithIdentifier:KcookieKey];
        if ([cookieData isKindOfClass:[NSData class]]) {
            if([cookieData length]) {
                NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookieData];
                [cookieArray addObjectsFromArray:cookies];
            }
        }
//    }
    return cookieArray;
}

+ (NSDictionary *)cookieParam {

    NSMutableDictionary *cookieDic = [NSMutableDictionary dictionary];
//    if ([GlobalConst isLoged]) {
        NSMutableString *cookieStr = [NSMutableString stringWithFormat:@""];
        NSMutableString *documentCookie = [NSMutableString stringWithFormat:@""];

        NSData *cookieData = [[self class] fetchObjectWithIdentifier:KcookieKey];
        if ([cookieData isKindOfClass:[NSData class]]) {
            if([cookieData length]) {
                NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookieData];
                
                for (NSHTTPCookie *cookie in cookies) {
                    [cookieDic setObject:cookie.value forKey:cookie.name];
                }
                for (NSString *key in cookieDic) {
                    NSString *appendString = [NSString stringWithFormat:@"%@=%@;", key, [cookieDic valueForKey:key]];
                    [cookieStr appendString:appendString];
                    
                    NSString *documentAppend = [NSString stringWithFormat:@"document.cookie='%@=%@';", key, [cookieDic valueForKey:key]];
                    [documentCookie appendString:documentAppend];
                }
                [cookieDic setObject:cookieStr forKey:@"cookieStr"];
                [cookieDic setObject:documentCookie forKey:@"documentCookie"];
            }
         }
//     }
     return cookieDic;
}

+ (void)deleteRequestCookie {
    
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *cookie in [storage cookies]) {
        [storage deleteCookie:cookie];
    }
}

//保存一个当前用户的值
+ (void)setUserValue:(NSString *)value key:(NSString *)key{
   
}

//取一个当前用户的值
+ (NSString *)getUserValue:(NSString *)key{
    return @"";
}

+ (BOOL)copyFileWithFromPath:(NSString *)fromPath toPath:(NSString *)toPath {
    NSFileManager* fm = [NSFileManager defaultManager];
    NSError *error = nil;
    if (![fm fileExistsAtPath:toPath]) {
        BOOL result = [fm copyItemAtPath:fromPath toPath:toPath error:&error];
        //文件移到指定路径下之后,删除原来的文件
        if (result) { [fm removeItemAtPath:fromPath error:&error]; }
    }
    return error == nil;
}

@end
